<?php
/**
 * Created by PhpStorm.
 * User: mr.lee
 * Date: 2018/6/4
 * Time: 上午11:24
 */

namespace app\apitemp\controller;

use Alipay\Alipayobj;
use app\common\controller\ActionLogs;
use app\common\controller\FeiePrint;
use app\common\controller\TemplateMsg;
use app\common\model\Agent;
use app\common\model\CardMember;
use app\common\model\Merchant;
use app\common\model\Paylog;
use app\common\model\WxOpen;
use think\Db;
use Wechat\Wxobjopen;

class NotCardPay extends Pub
{
    public function getpay($param, $pays)
    {
        $User = new Merchant();
        $Paylog = new Paylog();
        $machinfos = $User->where(array('id' => $param['merchantid']))->find();
        $kt = substr($param['auth_code'], 0, 2);
        if ($kt >= 25 && $kt <= 30) {
            if ($machinfos['ali_merid'] !== '') {
                $pays['pay_fs'] = 3;
                if (isset($oldorder) && $oldorder['pay_statu'] == 0) {
                    $param['orderid'] = $param['out_trade_no'];
                    $Paylog->save($pays, ['orderid' => $param['out_trade_no']]);
                } else {
                    $pays['orderid'] = $param['orderid'];
                    $Paylog->save($pays);
                }

                return $this->alipay($param);
            } else {
                $rarr['return_code'] = "SUCCESS";
                $rarr['return_msg'] = '';
                $rarr['result_code'] = 'FAIL';
                $rarr['result_msg'] = '该商户未开通支付宝支付通道';
            }
        } elseif ($kt >= 10 && $kt <= 15) {
            if ($machinfos['sub_mch_id'] !== '') {
                $pays['pay_fs'] = 2;
                if (isset($oldorder) && $oldorder['pay_statu'] == 0) {
                    $param['orderid'] = $param['out_trade_no'];
                    $Paylog->save($pays, ['orderid' => $param['out_trade_no']]);
                } else {
                    $pays['orderid'] = $param['orderid'];
                    $Paylog->save($pays);
                }
                return $this->wxpay($param);
            } else {
                $rarr['return_code'] = "SUCCESS";
                $rarr['return_msg'] = '';
                $rarr['result_code'] = 'FAIL';
                $rarr['result_msg'] = '该商户未开通微信支付通道';
            }

        } else {
            $rarr['return_code'] = "SUCCESS";
            $rarr['return_msg'] = '';
            $rarr['result_code'] = 'FAIL';
            $rarr['result_msg'] = '条码格式错误';
        }
        return $rarr;

    }


    //微信支付
    public function wxpay($param)
    {


        try {

            $map['id'] = $param['merchantid'];
            $Merchant = new Merchant();
            $Agent = new Agent();
            $WxOpen = new WxOpen();
            $config = $Merchant->where($map)->find();
            $agent = $Agent->where(array('id' => $config['agent']))->find();
            $users = $WxOpen->where(array('id' => $agent['wx_open_id']))->find();
            $options = array(
                'appid' => $users['authorizer_appid'], // 填写高级调用功能的app id
                'partnerid' => $agent['partnerid'], // 财付通商户身份标识
                'partnerkey' => $agent['partnerkey'], // 财付通商户权限密钥Key
            );
            $sh = $param['merchantid'];
            $weObj = new Wxobjopen($options);
            //充值


            $pay_fees = $param['total_fee'];

            //END
            //支付金额保留两位小数
            $price = $this->format_price($pay_fees);
            //END
            $out_trade_no = $param['orderid'];
            $body = "快捷支付";

            $wx_param = array(
                "appid" => $users['authorizer_appid'],
                'sub_appid' => "",
                "mch_id" => $agent['partnerid'],
                "sub_mch_id" => $config['sub_mch_id'],
                "nonce_str" => $weObj->generateNonceStr(),
                "body" => $body,
                "out_trade_no" => $param['orderid'],
                "total_fee" => $price * 100,
                "spbill_create_ip" => $param['client_ip'],
                "auth_code" => $param['auth_code'],
            );
            $pay_xml = $weObj->createWxPackageXml($wx_param);
            $pay_xml = $weObj->Mircopay_post($pay_xml);

            $rarr = $this->wxpay_statu($pay_xml, $sh, $out_trade_no);


        } catch (\Exception $e) {
            $rarr['return_code'] = "FAIL";
            $rarr['return_msg'] = '系统错误';
            $rarr['result_code'] = 'FAIL';
            $rarr['result_msg'] = '系统错误' . $e->getMessage();
        }
        return $rarr;


    }

    public function wxpay_statu($pay_xml, $id, $orderid)
    {
        try {
            $Paylog = new Paylog();
            $payinfoa = $Paylog->where(['orderid' => $orderid])->find();

            if ($payinfoa['pay_fs'] == 0 || $payinfoa['pay_fs'] == 2) {
                if ($pay_xml['return_code'] == "SUCCESS") {
                    if ($pay_xml['result_code'] == "FAIL") {

                        $arrc['return_code'] = "SUCCESS";
                        if ($pay_xml['err_code'] == "USERPAYING") {
                            $arrc['result_code'] = $pay_xml['err_code'];
                        } else {
                            $arrc['result_code'] = "FAIL";
                        }
                        $arrc['return_msg'] = translate($pay_xml['err_code']);
                        $arrc['result_msg'] = translate($pay_xml['err_code_des']);
                        $arrc['out_trade_no'] = $payinfoa['orderid'];
                        $arrc['trade_no'] = $payinfoa['trade_no'];


                    } else {
                        if ($pay_xml['return_code'] && $pay_xml['result_code'] != "SUCCESS") {
                            $arrc['return_code'] = "SUCCESS";
                            $arrc['result_code'] = "FAIL";
                            $arrc['return_msg'] = translate($pay_xml['err_code']);
                            $arrc['result_msg'] = translate($pay_xml['err_code_des']);
                        } elseif (isset($pay_xml['trade_state']) && $pay_xml['trade_state'] != "SUCCESS") {
                            $arrc['return_code'] = "SUCCESS";
                            if ($pay_xml['trade_state'] == "USERPAYING") {
                                $arrc = $this->getorderinfo($orderid);
                                $arrc['result_code'] = "USERPAYING";
                                $arrc['out_trade_no'] = $payinfoa['orderid'];
                                $arrc['trade_no'] = $payinfoa['trade_no'];
                            } else {
                                $arrc['result_code'] = "FAIL";
                            }
                            $arrc['result_code'] = $pay_xml['trade_state'];
                            $arrc['return_msg'] = translate($pay_xml['trade_state']);
                            $arrc['result_msg'] = translate($pay_xml['trade_state']);
                        } else {
                            $pays['orderno'] = $pay_xml['transaction_id'];
                            $pays['pay_time'] = date('Y-m-d H:i:s', strtotime($pay_xml['time_end']));
                            $pays['pay_statu'] = 1;
                            $pays['openid'] = $pay_xml['openid'];
                            $pays['sub_openid'] = isset($pay_xml['sub_openid']) ? $pay_xml['sub_openid'] : "";
                            $pays['payinfo'] = json_encode($pay_xml);
                            $pays['price'] = $pay_xml['total_fee'] / 100;
                            $Pub = new Pub();
                            $pays['service_charge'] = $Pub->service_charge($payinfoa['mid'], $pays['price'], $payinfoa['pay_fs']);
                            $Paylog->save($pays, ['orderid' => $orderid]);
                            $TemplateMsg = new TemplateMsg();
                            $TemplateMsg->send_tpl('pay', array('merchantid' => $id, 'orderid' => $orderid));
                            $FeiePrint = new FeiePrint();
                            $FeiePrint->sendprint($orderid);
                            //返回结果
                            $arrc = $this->getorderinfo($orderid);

                        }

                    }
                } elseif ($pay_xml['return_code'] == "FAIL") {
                    $arrc['return_code'] = "SUCCESS";
                    $arrc['result_code'] = "FAIL";
                    $arrc['return_msg'] = translate($pay_xml['return_msg']);
                    $arrc['result_msg'] = translate($pay_xml['return_msg']);
                }
            } elseif ($payinfoa['pay_fs'] == 8) {
                if ($payinfoa['pay_statu'] == 1) {


                    $TemplateMsg = new TemplateMsg();
                    $TemplateMsg->send_tpl('pay', array('merchantid' => $id, 'orderid' => $orderid));
                    $FeiePrint = new FeiePrint();
                    $FeiePrint->sendprint($orderid);
                    $arrc = $this->getorderinfo($orderid);
                } else {
                    $arrc['return_code'] = "SUCCESS";
                    $arrc['result_code'] = "FAIL";
                    $arrc['return_msg'] = "支付失败";
                    $arrc['result_msg'] = "支付失败";
                }
            }


        } catch (\Exception $e) {
            $arrc['return_code'] = "FAIL";
            $arrc['return_msg'] = '系统错误';
            $arrc['result_code'] = 'FAIL';
            $arrc['result_msg'] = '系统错误' . $e->getMessage();
        }
        return $arrc;


    }

    public function getcheckpay($param, $pay_fs)
    {
        if ($pay_fs) {
            switch ($pay_fs) {
                case '0':
                    $rarr = $this->wxcheckpay($param);
                    break;
                case '1':
                    $rarr = $this->alicheckpay($param);
                    break;
                case '2':
                    $rarr = $this->wxcheckpay($param);
                    break;
                case '3':
                    $rarr = $this->alicheckpay($param);
                    break;
                case '8':
                    $rarr = $this->wxcheckpay($param);
                    break;
            }
        } else {
            $rarr['return_code'] = "SUCCESS";
            $rarr['result_code'] = 'FAIL';
            $rarr['return_msg'] = '订单编号不存在';
            $rarr['result_msg'] = "订单编号不存在";
        }
        return $rarr;
    }

    public function wxcheckpay($param)
    {
        try {
            $orderid = $param['out_trade_no'];

            $id = $param['merchantid'];
            $payxml = $this->wxorderquery($id, $orderid);
            $rarr = $this->wxpay_statu($payxml, $id, $orderid);


        } catch (\Exception $e) {
            $rarr['return_code'] = "FAIL";
            $rarr['return_msg'] = '系统错误';
            $rarr['result_code'] = 'FAIL';
            $rarr['result_msg'] = '系统错误' . $e->getMessage();
        }

        return $rarr;


    }

    public function wxorderquery($id, $orderid)
    {

        try {
            $map['id'] = $id;
            $config = Db::name('Merchant')->where($map)->find();
            $agent = Db::name('agent')->where(array('id' => $config['agent']))->find();
            $users = Db::name('wx_open')->where(array('id' => $agent['wx_open_id']))->find();

            $options = array(
                'appid' => $users['authorizer_appid'], // 填写高级调用功能的app id
                'partnerid' => $agent['partnerid'], // 财付通商户身份标识
                'partnerkey' => $agent['partnerkey'], // 财付通商户权限密钥Key
            );

            $weObj = new Wxobjopen($options);
            $arrdata = array(
                "appid" => $users['authorizer_appid'],
                "mch_id" => $agent['partnerid'],
                "sub_appid" => "",
                "sub_mch_id" => $config['sub_mch_id'],
                "nonce_str" => $weObj->generateNonceStr(),
                "out_trade_no" => $orderid
            );
            $orderxml = $weObj->createWxPackageXml($arrdata);

            $rarr = $weObj->getPayNum($orderxml);

        } catch (\Exception $e) {
            $rarr['return_code'] = "FAIL";
            $rarr['return_msg'] = '系统错误';
            $rarr['result_code'] = 'FAIL';
            $rarr['result_msg'] = '系统错误' . $e->getMessage();;
        }
        return $rarr;

    }

    //支付宝
    public function alipay($param)
    {
        try {
            $User = new Merchant();
            $Agent = new Agent();
            $users = $User->where(array('id' => $param['merchantid']))->find();
            $agent = $Agent->where(array('id' => $users['agent']))->find();
            $options = array(
                'appid' => $agent['ali_app_id'], // 填写高级调用功能的app id
                'rsaPrivateKey' => $agent['ali_app_key'],
            );
            $aliObj = new Alipayobj($options);
            $price = $param['total_fee'];
            $sh = $param['merchantid'];
            $out_trade_no = $param['orderid'];
            $body = "快捷支付";
            $auth_code = $param['auth_code'];
            $total_fee = $price;
            $data['app_id'] = $agent['ali_app_id'];
            $data['method'] = "alipay.trade.pay";
            $data['charset'] = "UTF-8";
            $data['sign_type'] = "RSA2";
            $data['timestamp'] = date('Y-m-d H:i:s');
            $data['version'] = "1.0";
            $data['notify_url'] = 'http://api.wunengkeji.com/';
            $data['app_auth_token'] = $users['ali_merid'];
            $data['biz_content'] = json_encode(array(
                'out_trade_no' => $out_trade_no,
                'scene' => 'bar_code',
                'auth_code' => $auth_code,
                'total_amount' => $total_fee,
                'subject' => $body,
                'alipay_store_id' => $users['ali_store_id'],
//                'store_id'=>I('get.id'),
                'extend_params' => array(
                    'sys_service_provider_id' => $agent['sys_service_provider_id'],
                ),
            ));
            $signContent = $aliObj->rsaSign($data, $signType = "RSA2");
            $data['sign'] = $signContent;
            $sj = $aliObj->scanpay($data);
            $content = json_decode(iconv("GB2312", "UTF-8//IGNORE", $sj), true);
            $rarr = $this->alipay_statu($content['alipay_trade_pay_response'], $sh, $out_trade_no);


        } catch (\Exception $e) {
            $rarr['return_code'] = "FAIL";
            $rarr['return_msg'] = '系统错误';
            $rarr['result_code'] = 'FAIL';
            $rarr['result_msg'] = '系统错误' . $e->getMessage();;
        }
        return $rarr;

    }

    public function alipay_statu($contents, $sh, $orderid, $fs = '')
    {

        try {
//            return $contents;
            $Paylog = new Paylog();
            $payinfo = $Paylog->where(['orderid' => $orderid])->find();
            if ($payinfo['pay_fs'] == 1 || $payinfo['pay_fs'] == 3) {
                if ($fs == "checkpay") {


                    if ($contents['code'] == 10000) {
                        switch ($contents['trade_status']) {
                            case 'WAIT_BUYER_PAY':

                                $arrc['return_code'] = "SUCCESS";
                                $arrc['result_code'] = "USERPAYING";
                                $arrc['return_msg'] = translate($contents['trade_status']);
                                $arrc['result_msg'] = translate($contents['trade_status']);
                                $arrc['out_trade_no'] = $payinfo['orderid'];
                                $arrc['trade_no'] = $payinfo['trade_no'];
                                break;
                            case 'TRADE_CLOSED':
                                $arrc['return_code'] = "SUCCESS";
                                $arrc['result_code'] = "FAIL";
                                $arrc['return_msg'] = translate($contents['trade_status']);
                                $arrc['result_msg'] = translate($contents['trade_status']);
                                break;
                            case 'TRADE_FINISHED':
                                $arrc['return_code'] = "SUCCESS";
                                $arrc['result_code'] = "FAIL";
                                $arrc['return_msg'] = translate($contents['trade_status']);
                                $arrc['result_msg'] = translate($contents['trade_status']);
                                break;
                            case 'TRADE_SUCCESS':
                                $pays['pay_statu'] = 1;
                                $pays['orderno'] = $contents['trade_no'];
                                $pays['pay_time'] = $contents['send_pay_date'];
                                $pays['price'] = $contents['total_amount'];
                                $pays['openid'] = $contents['buyer_user_id'];
                                $pays['payinfo'] = json_encode($contents);
                                $Pub = new Pub();
                                $pays['service_charge'] = $Pub->service_charge($payinfo['mid'], $pays['price'], $payinfo['pay_fs']);
                                $Paylog = new Paylog();
                                $Paylog->save($pays, ['orderid' => $orderid]);
                                $TemplateMsg = new TemplateMsg();
                                $TemplateMsg->send_tpl('pay', array('merchantid' => $payinfo['mid'], 'orderid' => $orderid));
                                $FeiePrint = new FeiePrint();
                                $FeiePrint->sendprint($orderid);
                                $arrc = $this->getorderinfo($orderid);
                                break;
                        }


                    } else {
                        $arrc['return_code'] = "SUCCESS";
                        $arrc['result_code'] = "FAIL";
                        $arrc['return_msg'] = translate($contents['code']);
                        $arrc['result_msg'] = translate($contents['code']);
                    }

                } else {
                    if ($contents['code'] == 10000) {

                        if ($contents['msg'] = "Success") {

                            $pays['pay_statu'] = 1;
                            $pays['openid'] = $contents['buyer_user_id'];
                            $pays['orderno'] = $contents['trade_no'];
                            $pays['pay_time'] = $contents['gmt_payment'];
                            $pays['price'] = $contents['total_amount'];
                            $pays['payinfo'] = json_encode($contents);
                            $Pub = new Pub();
                            $pays['service_charge'] = $Pub->service_charge($payinfo['mid'], $pays['price'], $payinfo['pay_fs']);
                            $Paylog = new Paylog();
                            $Paylog->save($pays, ['orderid' => $orderid]);
                            $TemplateMsg = new TemplateMsg();
                            $TemplateMsg->send_tpl('pay', array('merchantid' => $payinfo['mid'], 'orderid' => $orderid));
                            $FeiePrint = new FeiePrint();
                            $FeiePrint->sendprint($orderid);
                            $arrc = $this->getorderinfo($orderid);

                        }
                    } elseif ($contents['code'] == 10003) {
                        $arrc['return_code'] = "SUCCESS";
                        $arrc['result_code'] = "USERPAYING";
                        $arrc['return_msg'] = "等待用户输入密码";
                        $arrc['result_msg'] = "等待用户输入密码";
                        $arrc['out_trade_no'] = $payinfo['orderid'];
                        $arrc['trade_no'] = $payinfo['trade_no'];
                    } elseif ($contents['code'] = 40004) {
                        $arrc['return_code'] = "SUCCESS";
                        $arrc['result_code'] = "FAIL";
                        $arrc['return_msg'] = translate($contents['sub_msg']);
                        $arrc['result_msg'] = translate($contents['sub_msg']);

                    }
                }
            }
        } catch (\Exception $e) {
            $arrc['return_code'] = "FAIL";
            $arrc['return_msg'] = '系统错误';
            $arrc['result_code'] = 'FAIL';
            $arrc['result_msg'] = '系统错误' . $e->getMessage();
        }
        return $arrc;
    }

    public function alicheckpay($param)
    {

        try {
            $orderid = $param['out_trade_no'];
            $id = $param['merchantid'];
            $payxml = $this->aliorderquery($id, $orderid);
            $rarr = $this->alipay_statu($payxml['alipay_trade_query_response'], $id, $orderid, "checkpay");

        } catch (\Exception $e) {
            $rarr['return_code'] = "FAIL";
            $rarr['return_msg'] = '系统错误';
            $rarr['result_code'] = 'FAIL';
            $rarr['result_msg'] = '系统错误' . $e->getMessage();
        }
        return $rarr;


    }

    public function aliorderquery($id, $orderid)
    {

        $User = new Merchant();
        $Agent = new Agent();
        $users = $User->where(array('id' => $id))->find();
        $agent = $Agent->where(array('id' => $users['agent']))->find();

        $options = array(

            'appid' => $agent['ali_app_id'], // 填写高级调用功能的app id
            'rsaPrivateKey' => $agent['ali_app_key'],

        );
        $out_trade_no = $orderid;
        $aliObj = new Alipayobj($options);
        $data['app_id'] = $agent['ali_app_id'];
        $data['method'] = "alipay.trade.query";
        $data['charset'] = "UTF-8";
        $data['sign_type'] = "RSA2";
        $data['timestamp'] = date('Y-m-d H:i:s');
        $data['version'] = "1.0";
        $data['notify_url'] = 'https://tp5.weilinzhou.com';
        $data['app_auth_token'] = $users['ali_merid'];
        $data['biz_content'] = json_encode(array(
            'out_trade_no' => $out_trade_no,
        ));
        $signContent = $aliObj->rsaSign($data, $signType = "RSA2");
        $data['sign'] = $signContent;
        $sj = $aliObj->scanpay($data);
        return $content = json_decode(iconv("GB2312", "UTF-8//IGNORE", $sj), true);


    }


}